import {
  reqLogin,
  reqMulti,
  reqQUserInfo,
  reqRegister,
  reqUserInfo,
  reqUserupdate,
} from '@/api/user'
import { loginForm, respLoginData } from '@/api/user/types'
import { defineStore } from 'pinia'
import type { UserState } from './types/types'
// import { GET_TOKEN, SET_TOKEN } from '@/utils/token'
//引入常量路由
import { constantRoutes } from '@/router/routes'
import {
  getqAT,
  getqEU,
  getToken,
  removeToken,
  setAccessToken,
  setqAT,
  setqEU,
  setqRT,
  setRefreshToken,
} from '@/utils/auth'
import axios from 'axios'
import { reqRefreshToken } from '@/api/qyyjt'

let useUserStore = defineStore('User', {
  // 数据
  state: (): UserState => {
    return {
      accessToken: getToken(),
      refreshToken: '',
      menuRoutes: constantRoutes,
      username: '',
      avatar: '',
      testMsg: '',
      userObj: {},
      qUserObj: {
        pcuss: getqAT(),
        user: getqEU(),
      },
    }
  },
  actions: {
    async login(data: loginForm) {
      let resp: respLoginData = await reqLogin(data)
      if (resp.code === 200) {
        this.accessToken = resp.data.access_token as string
        this.refreshToken = resp.data.refresh_token as string
        console.log('##', this.accessToken, '@@', this.refreshToken)
        setAccessToken(this.accessToken)
        setRefreshToken(this.refreshToken)
        // console.log(999,resp.data.access_token, resp.data.refresh_token);
        return 'OK' // 保证返回的promise是一个成功的
      } else {
        console.log(resp)
        return Promise.reject(new Error(resp.data.msg))
      }
    },
    async registerUser(data) {
      let resp: any = await reqRegister(data)
      console.log(resp)
      if (resp.code === 200) {
        return 'OK'
      } else {
        return Promise.reject(new Error(resp.msg))
      }
    },
    async userInfo() {
      let resp = await reqUserInfo()
      // console.log('userLogin',resp);
      if (resp.code === 200) {
        // console.log(resp.data)
        this.username = resp.data.username
        this.avatar = resp.data.avatar
        this.userObj = resp.data
        return 'OK' // 异步返回时promise，undefined也是成功
      } else {
        return Promise.reject('获取用户信息失败，请重新登录。')
      }
    },
    async userUpdate(data) {
      let resp = await reqUserupdate(data)
      if (resp.code === 200) {
        await this.userInfo() // 更新完后重新刷新一下用户信息
      }
    },
    async testMulti() {
      let resp = await reqMulti()
      if (resp.code === 200) {
        this.testMsg = resp.data.test
        // this.username = resp.data.username
        // this.avatar = resp.data.avatar
        return 'OK' // 异步返回时promise，undefined也是成功
      } else {
        return Promise.reject('获取用户信息失败，请重新登录。')
      }
    },
    async refreshTokenAction(config) {
      const newConfig = Object.assign({}, config) //这里的config修改一定要用复制，而非引用
      newConfig.headers.Authorization =
        'Bearer ' + localStorage.getItem('refreshToken')
      newConfig.url = '/refresh_token'
      newConfig.method = 'post'
      let resp = await axios(newConfig)
      if (resp.status === 200) {
        // 原始axios状态码在status中
        setAccessToken(resp.data.data.access_token)
        return 'OK'
      } else {
        return Promise.reject('刷新失败')
      }
    },
    async verfyQToken() {
      // let qObj = {q_rtk: this.userObj.R_TK,q_enc_user:this.userObj.EncUser}
      // console.log(qObj);
      // let resp = await reqRefreshToken(qObj)
      let resp = await reqRefreshToken({
        q_rtk: this.userObj.R_TK,
        q_enc_user: this.userObj.EncUser,
      })
      if (resp.data.info === 'success') {
        this.userObj.A_TK = resp.data.data.accessToken
        setqAT(this.userObj.A_TK)
        setqRT(this.userObj.R_TK)
        setqEU(this.userObj.EncUser)
        await reqQUserInfo({ A_TK: this.userObj.A_TK })
        return resp.data.info // 成功了就返回success
      } else {
        return Promise.reject(new Error('Q刷新Token失效'))
      }
    },
    logout() {
      this.accessToken = ''
      this.refreshToken = ''
      this.username = ''
      this.avatar = ''
      removeToken()
    },
  },
  getters: {},
})

export default useUserStore
